package com.crazy.crazytransactionservice.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crazy.crazymodel.model.entity.Product;
import com.crazy.crazymodel.model.vo.GetTransactionVO;
import com.crazy.crazyserviceclient.service.ProductFeignClient;
import com.crazy.crazytransactionservice.dto.TransactionQueryRequest;
import com.crazy.crazymodel.model.entity.Transaction;
import com.crazy.crazytransactionservice.mapper.TransactionMapper;
import com.crazy.crazytransactionservice.service.TransactionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @Date: 2024-05-16-14:01
 * @Author: Zheng Zeliang
 */
@Service
@Slf4j
public class TransactionServiceImpl extends ServiceImpl<TransactionMapper, Transaction> implements TransactionService {
    @Resource
    private TransactionMapper transactionMapper;
    @Resource
    private ProductFeignClient productFeignClient;

    @Override
    public Page<GetTransactionVO> listTransactionByQueryRequest(TransactionQueryRequest transactionQueryRequest) {
        Page<GetTransactionVO> page = new Page<>(transactionQueryRequest.getCurrent(), transactionQueryRequest.getPageSize());
        transactionQueryRequest.setStartIndex(transactionQueryRequest.genStartIndex());
        log.info("开始位置为：{}",transactionQueryRequest.getStartIndex());
        List<Transaction> transactions = transactionMapper.selectTransactionByQueryRequest(transactionQueryRequest);
        if (transactions.size() == 0) {
            page.setRecords(null);
            page.setTotal(0);
            return page;
        }
        List<GetTransactionVO> getTransactionVOS = new ArrayList<>();
        for (Transaction transaction : transactions) {
            Integer productID = transaction.getProductID();
            GetTransactionVO getTransactionVO = new GetTransactionVO();
            BeanUtils.copyProperties(transaction, getTransactionVO);
            Product product = productFeignClient.getById(productID);
            getTransactionVO.setProductCode(product.getProductCode());
            getTransactionVO.setProductName(product.getProductName());
            getTransactionVO.setProductType(product.getProductType());
            getTransactionVO.setProductRisk(product.getRiskLevel());
            getTransactionVOS.add(getTransactionVO);
        }
        page.setRecords(getTransactionVOS);
        page.setTotal(getTransactionVOS.size());
        return page;
    }
}
